import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';

import '../models/mood_record.dart';
import '../models/mood_type.dart';

import '../providers/mood_provider.dart';


import '../widgets/media_preview.dart';



/// 情绪记录详情页面
/// 显示单个情绪记录的完整信息，支持查看、编辑和删除
class MoodDetailScreen extends StatefulWidget {
  /// 情绪记录ID
  final String recordId;

  const MoodDetailScreen({
    super.key,
    required this.recordId,
  });

  @override
  State<MoodDetailScreen> createState() => _MoodDetailScreenState();
}

class _MoodDetailScreenState extends State<MoodDetailScreen>
    with TickerProviderStateMixin {
  /// 动画控制器
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  /// 是否处于编辑模式
  bool _isEditing = false;

  /// 编辑控制器
  late TextEditingController _contentController;
  late TextEditingController _tagsController;

  /// 当前记录
  MoodRecord? _currentRecord;

  /// 是否正在加载
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _initializeControllers();
    _loadRecord();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _contentController.dispose();
    _tagsController.dispose();
    super.dispose();
  }

  /// 初始化动画
  void _initializeAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));

    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeOutCubic,
    ));
  }

  /// 初始化文本控制器
  void _initializeControllers() {
    _contentController = TextEditingController();
    _tagsController = TextEditingController();
  }

  /// 加载情绪记录
  Future<void> _loadRecord() async {
    try {
      final provider = Provider.of<MoodProvider>(context, listen: false);
      final record = await provider.getRecordById(widget.recordId);
      
      if (record != null) {
        setState(() {
          _currentRecord = record;
          _contentController.text = record.content ?? '';
          _tagsController.text = record.tags.join(', ');
          _isLoading = false;
        });
        _animationController.forward();
      } else {
        _showErrorAndGoBack('记录不存在');
      }
    } catch (e) {
      _showErrorAndGoBack('加载记录失败: $e');
    }
  }

  /// 显示错误并返回
  void _showErrorAndGoBack(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.red,
        ),
      );
      Navigator.of(context).pop();
    }
  }

  /// 切换编辑模式
  void _toggleEditMode() {
    setState(() {
      _isEditing = !_isEditing;
      if (!_isEditing && _currentRecord != null) {
        // 退出编辑模式时重置内容
        _contentController.text = _currentRecord!.content ?? '';
        _tagsController.text = _currentRecord!.tags.join(', ');
      }
    });
  }

  /// 保存编辑
  Future<void> _saveEdit() async {
    if (_currentRecord == null) return;

    try {
      final provider = Provider.of<MoodProvider>(context, listen: false);
      
      final updatedRecord = _currentRecord!.copyWith(
        diaryContent: _contentController.text.trim(),
        tags: _tagsController.text
            .split(',')
            .map((tag) => tag.trim())
            .where((tag) => tag.isNotEmpty)
            .toList(),
        updatedAt: DateTime.now(),
      );

      await provider.updateRecord(updatedRecord);
      
      setState(() {
        _currentRecord = updatedRecord;
        _isEditing = false;
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('保存成功'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('保存失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 删除记录
  Future<void> _deleteRecord() async {
    final confirmed = await _showDeleteConfirmDialog();
    if (!confirmed || !mounted) return;

    final provider = Provider.of<MoodProvider>(context, listen: false);
    try {
      await provider.deleteRecord(widget.recordId);
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('删除成功'),
            backgroundColor: Colors.green,
          ),
        );
        
        Navigator.of(context).pop();
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 显示删除确认对话框
  Future<bool> _showDeleteConfirmDialog() async {
    return await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这条情绪记录吗？此操作无法撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    ) ?? false;
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('情绪详情'),
        ),
        body: const Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    if (_currentRecord == null) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('情绪详情'),
        ),
        body: const Center(
          child: Text('记录不存在'),
        ),
      );
    }

    return Scaffold(
      appBar: _buildAppBar(),
      body: FadeTransition(
        opacity: _fadeAnimation,
        child: SlideTransition(
          position: _slideAnimation,
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildHeader(),
                const SizedBox(height: 24),
                _buildMoodSection(),
                const SizedBox(height: 24),
                _buildContentSection(),
                const SizedBox(height: 24),
                _buildTagsSection(),
                const SizedBox(height: 24),
                _buildMediaSection(),
                const SizedBox(height: 24),
                _buildMetadataSection(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: const Text('情绪详情'),
      actions: [
        if (_isEditing) ...[
          IconButton(
            icon: const Icon(Icons.close),
            onPressed: _toggleEditMode,
            tooltip: '取消编辑',
          ),
          IconButton(
            icon: const Icon(Icons.check),
            onPressed: _saveEdit,
            tooltip: '保存',
          ),
        ] else ...[
          IconButton(
            icon: const Icon(Icons.edit),
            onPressed: _toggleEditMode,
            tooltip: '编辑',
          ),
          PopupMenuButton<String>(
            onSelected: (value) {
              switch (value) {
                case 'delete':
                  _deleteRecord();
                  break;
              }
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'delete',
                child: Row(
                  children: [
                    Icon(Icons.delete, color: Colors.red),
                    SizedBox(width: 8),
                    Text('删除', style: TextStyle(color: Colors.red)),
                  ],
                ),
              ),
            ],
          ),
        ],
      ],
    );
  }

  /// 构建头部信息
  Widget _buildHeader() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            Container(
              width: 60,
              height: 60,
              decoration: BoxDecoration(
                color: _currentRecord!.moodType.color.withValues(alpha: 0.2),
                borderRadius: BorderRadius.circular(30),
              ),
              child: Icon(
                _currentRecord!.moodType.icon,
                size: 30,
                color: _currentRecord!.moodType.color,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _currentRecord!.moodType.label,
                    style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    DateFormat('yyyy年MM月dd日 HH:mm').format(_currentRecord!.createdAt),
                    style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建情绪部分
  Widget _buildMoodSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '情绪强度',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            Row(
              children: [
                Expanded(
                  child: LinearProgressIndicator(
                    value: _currentRecord!.intensity / 10,
                    backgroundColor: Colors.grey[300],
                    valueColor: AlwaysStoppedAnimation<Color>(
                      _currentRecord!.moodType.color,
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Text(
                  '${_currentRecord!.intensity}/10',
                  style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建内容部分
  Widget _buildContentSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '日记内容',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            if (_isEditing)
              TextField(
                controller: _contentController,
                maxLines: 6,
                decoration: const InputDecoration(
                  hintText: '记录你的心情和想法...',
                  border: OutlineInputBorder(),
                ),
              )
            else
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.grey[50],
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.grey[300]!),
                ),
                child: Text(
                  _currentRecord!.diaryContent?.isNotEmpty == true
                      ? _currentRecord!.diaryContent!
                      : '暂无内容',
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建标签部分
  Widget _buildTagsSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '标签',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            if (_isEditing)
              TextField(
                controller: _tagsController,
                decoration: const InputDecoration(
                  hintText: '用逗号分隔多个标签',
                  border: OutlineInputBorder(),
                ),
              )
            else if (_currentRecord!.tags.isNotEmpty)
              Wrap(
                spacing: 8,
                runSpacing: 8,
                children: _currentRecord!.tags.map((tag) => Chip(
                  label: Text(tag),
                  backgroundColor: Theme.of(context).primaryColor.withValues(alpha: 0.1),
                )).toList(),
              )
            else
              Text(
                '暂无标签',
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                  color: Colors.grey[600],
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建媒体部分
  Widget _buildMediaSection() {
    if (_currentRecord!.mediaAttachments.isEmpty) {
      return const SizedBox.shrink();
    }

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '媒体文件',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                crossAxisSpacing: 8,
                mainAxisSpacing: 8,
              ),
              itemCount: _currentRecord!.mediaAttachments.length,
              itemBuilder: (context, index) {
                final attachment = _currentRecord!.mediaAttachments[index];
                return MediaPreview(
                  attachments: [attachment],
                  onRemove: (attachment) {},
                  readOnly: true,
                );
              },
            ),
          ],
        ),
      ),
    );
  }


  /// 构建元数据部分
  Widget _buildMetadataSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '记录信息',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            _buildMetadataRow('创建时间', DateFormat('yyyy-MM-dd HH:mm:ss').format(_currentRecord!.createdAt)),
            _buildMetadataRow('更新时间', DateFormat('yyyy-MM-dd HH:mm:ss').format(_currentRecord!.updatedAt)),
            _buildMetadataRow('媒体文件', '${_currentRecord!.mediaAttachments.length} 个'),
          ],
        ),
      ),
    );
  }

  /// 构建元数据行
  Widget _buildMetadataRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Colors.grey[600],
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: Theme.of(context).textTheme.bodyMedium,
            ),
          ),
        ],
      ),
    );
  }
}